package com.ruoyi.maode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.maode.domain.dto.DetectionResultDTO;
import com.ruoyi.maode.domain.entity.*;
import com.ruoyi.maode.domain.vo.ImageDetailVO;
import com.ruoyi.maode.domain.vo.PartSizeDataVO;
import com.ruoyi.maode.domain.vo.PartSizeDetailsVO;
import com.ruoyi.maode.domain.vo.PartSizeVO;
import com.ruoyi.maode.mapper.PartMapper;
import com.ruoyi.maode.mapper.PartSizeMapper;
import com.ruoyi.maode.service.*;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.util.LoadLibs;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;


/**
 * 零件检测实现类
 * @author zhangwenqiang
 */
@Service
public class PartSizeServiceImpl extends ServiceImpl<PartSizeMapper, PartSize> implements PartSizeService {

    @Value("${server.url}")
    private String serverUrl;

    @Autowired
    private PartSizeMapper partSizeMapper;

    @Autowired
    private PartService partService;

    @Autowired
    private PartBatchService partBatchService;

    @Autowired
    private PartImageService partImageService;

    @Autowired
    private PartReportService partReportService;


    @Override
    public PartSizeDataVO getPartSizeDetail(Long id,Integer type,Integer partId) {

        PartSizeDataVO partSizeDataVO = new PartSizeDataVO();
        // 组装参数
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("type", type);
        map.put("flag", 0);
        // 获取当前批次的零件是否满足每月抽检
        PartBatch partBatch = partBatchService.getOne(new LambdaQueryWrapper<PartBatch>()
                .eq(PartBatch::getPartId, Long.valueOf(partId))
                .orderByAsc(PartBatch::getCreateTime)
                .last("LIMIT 1"));
        // 判定当前时间与获取时间已经超出30天返回1次/月的检测尺寸
        Boolean aBoolean = DateUtils.DayCheck(new Date(), partBatch.getCreateTime());
        // 获取当前批次的零件是否每季度抽检尺寸
        Boolean bBoolean = DateUtils.QuarterCheck(new Date(), partBatch.getCreateTime());
        if (aBoolean) {
            map.put("flag", 1);
        }
        if (bBoolean) {
            map.put("flag", 2);
        }

        List<PartSizeVO> partSizeVOS = partSizeMapper.getPartSizeDetail(map);
        List<PartSizeDetailsVO> vo = new ArrayList<>();
        for (PartSizeVO partSizeVO : partSizeVOS) {
            PartSizeDetailsVO detailsVO = new PartSizeDetailsVO();
            String images = partSizeVO.getImages();
            // 将 partCodeString 转换为 List<String>，假设字段内容是用逗号分隔的
            List<String> imageList = Arrays.asList(images.split(","));
            List<ImageDetailVO> imageDetailVOS = new ArrayList<>();
            // 将转换后的 List<String> 设置到 detailsVO 的相应字段
            for (String url : imageList) {
                ImageDetailVO imageDetailVO = new ImageDetailVO();
                imageDetailVO.setUrl(serverUrl + url);
                imageDetailVO.setName(ImageUtils.getImageName(url));
                imageDetailVOS.add(imageDetailVO);
            }
            partSizeDataVO.setImageData(imageDetailVOS);
            partSizeDataVO.setPartBatchCode(partSizeVO.getPartBatchCode());
            partSizeDataVO.setPartName(partSizeVO.getPartName());
            partSizeDataVO.setPartCode(partSizeVO.getPartCode());
            partSizeDataVO.setPartId(Math.toIntExact(partSizeVO.getPartId()));
            partSizeDataVO.setPartBatchId(partSizeVO.getPartBatchId());
            // 判断此批次是否生成了报告创建了审批 0-否，1-是
            PartReport partReport = partReportService.getOne(new LambdaQueryWrapper<PartReport>().eq(PartReport::getBatchId, partSizeVO.getPartBatchId()));
            if (partReport != null){
                partSizeDataVO.setIsApprove(Integer.valueOf(Constants.CONSTANTS_ONE));
            } else {
                partSizeDataVO.setIsApprove(Integer.valueOf(Constants.CONSTANTS_ZERO));
            }
            if (partSizeVO.getInspectorId() != null) {
                partSizeDataVO.setInspectorId(partSizeVO.getInspectorId());
            }
            if (partSizeVO.getInspectorName() != null) {
                partSizeDataVO.setInspectorName(partSizeVO.getInspectorName());
            }

            // 复制其他字段
            detailsVO.setId(partSizeVO.getId());
            detailsVO.setSerialNumber(partSizeVO.getSerialNumber());
            detailsVO.setPartId(partSizeVO.getPartId());
            detailsVO.setDetection(partSizeVO.getDetection());
            detailsVO.setMax(partSizeVO.getMax());
            detailsVO.setMin(partSizeVO.getMin());
            detailsVO.setTestMethod(partSizeVO.getTestMethod());
            List<String> measure = new ArrayList<>();
            if (partSizeVO.getMeasuredValue() != null) {
                measure = Arrays.asList(partSizeVO.getMeasuredValue().split(","));
            }
            // 判定是否需要手动判定结果（非数字的情况）
            // 判断最大值或者最小值是否为数字（包括整数和小数）
            if (!partSizeVO.getMax().matches("-?\\d*(\\.\\d+)?") || !partSizeVO.getMin().matches("-?\\d*(\\.\\d+)?")) {
                detailsVO.setIsJudge(Integer.valueOf(Constants.CONSTANTS_ONE));
            } else {
                detailsVO.setIsJudge(Integer.valueOf(Constants.CONSTANTS_ZERO));
            }
            detailsVO.setMeasuredValue(measure);
            detailsVO.setResult(partSizeVO.getResult());

            // 将转换后的 VO 对象加入到 vo 列表中
            vo.add(detailsVO);
        }

        partSizeDataVO.setPartSizeData(vo);

        return partSizeDataVO;
    }

    @Override
    public List<ImageDetailVO> getPartSizeImg(String partCode) {
        Part part = partService.getOne(new LambdaQueryWrapper<Part>()
                .eq(Part::getPartCode, partCode).eq(Part::getIsDelete,Constants.CONSTANTS_ZERO));
        Long partId = part.getId();
        PartImage partImage = partImageService.getOne(new LambdaQueryWrapper<PartImage>().eq(PartImage::getPartId, partId));
        List<String> imageList = Arrays.asList(partImage.getImage().split(","));

        List<ImageDetailVO> imageDetailVOS = new ArrayList<>();

        // 气泡图地址加上服务器地址url
        for (String url : imageList) {
            ImageDetailVO imageDetailVO = new ImageDetailVO();
            imageDetailVO.setUrl(serverUrl + url);
            imageDetailVO.setName(ImageUtils.getImageName(url));
            imageDetailVOS.add(imageDetailVO);
        }
        return imageDetailVOS;
    }

    // 方法：将 PNG 图像转换为 Excel 文件
    public static void convertPngToExcel(String imagePath, String excelPath) {
        try {
            // 初始化 Tesseract OCR
            File tessDataFolder = LoadLibs.extractTessResources("C:/Users/Administrator/Desktop/tessdata"); // 自动加载 tessdata 文件
            ITesseract instance = new Tesseract();
            instance.setDatapath(tessDataFolder.getAbsolutePath());

            // 使用 OCR 提取图像中的文本
            String result = instance.doOCR(new File(imagePath));

            // 将 OCR 结果解析为表格
            List<List<String>> tableData = parseTableFromText(result);

            // 创建 Excel 文件
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");

            // 将提取的表格数据写入 Excel 文件
            for (int rowIndex = 0; rowIndex < tableData.size(); rowIndex++) {
                Row row = sheet.createRow(rowIndex);
                List<String> rowData = tableData.get(rowIndex);
                for (int colIndex = 0; colIndex < rowData.size(); colIndex++) {
                    Cell cell = row.createCell(colIndex);
                    cell.setCellValue(rowData.get(colIndex));
                }
            }

            // 写入文件
            try (FileOutputStream fileOut = new FileOutputStream(excelPath)) {
                workbook.write(fileOut);
            }
            workbook.close();
            System.out.println("Excel 文件已保存到: " + excelPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 方法：解析 OCR 提取的文本为表格数据
    public static List<List<String>> parseTableFromText(String text) {
        List<List<String>> tableData = new ArrayList<>();
        String[] lines = text.split("\n");
        for (String line : lines) {
            // 假设表格是通过空格或制表符分隔的
            String[] cells = line.split("\\s+");
            if (cells.length > 0) {
                tableData.add(Arrays.asList(cells));
            }
        }
        return tableData;
    }
}
